<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'maintenance:management:inMaintenanceInfo:edit'"
    @register="registerMaintenancerModal"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="ViewsMaintenanceManagementInMaintenanceInfoForm">
  import { ref, unref, computed,defineProps,watch,onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {empUserListData} from '/@/api/sys/empUser';
  import { InMaintenanceInfo, inMaintenanceInfoSave, inMaintenanceInfoForm,inMaintenanceInfoUpdateUserCode } from '/@/api/maintenance.management/inMaintenanceInfo';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('maintenance.management.inMaintenanceInfo');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InMaintenanceInfo>({} as InMaintenanceInfo);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('维保维保人员') : t('编辑维保人员'),
  }));

  const props = defineProps({
    MaintenancerRecord: {
    type: Object,
  }
});
console.log('props初始值为', props.MaintenancerRecord)
const maintenanceParams=ref<Recordable>({
  name: '',
});

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('维保人员姓名'),
      field: 'userCode',
      fieldLabel:'userName',
      component: 'TreeSelect',
      componentProps: () => {
          return {
              api: empUserListData,
              params: maintenanceParams.value,
              fieldNames: { label: 'userName', value: 'userCode' },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              filterOption: false,
              allowClear: true,
              immediate: true,
              onSearch: (value: string) => {
                maintenanceParams.value.userName = value;
              }
          };
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerMaintenancerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    await resetFields();
    const res = await inMaintenanceInfoForm(data);
    record.value = (res.inMaintenanceInfo || {}) as InMaintenanceInfo;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      let data = await validate();
      console.log('mandata',data)
      data={
        ...data,
        enterpriseId:recordValue.value.enterpriseId,
        enterpriseName:recordValue.value.enterpriseName,
        maintenanceEnterpriseId:recordValue.value.maintenanceEnterpriseId,
        maintenanceEnterpriseName:recordValue.value.maintenanceEnterpriseName,
        startExecuteTime:recordValue.value.startExecuteTime,
        endExecuteTime:recordValue.endExecuteTime,
        state:recordValue.value.state,
        taskEndDate:recordValue.value.taskEndDate,
        taskStartDate:recordValue.value.taskStartDate,
        title:recordValue.value.title,
        completeTime:recordValue.value.completeTime,
        contractId:recordValue.value.contractId,
        executeMonth:recordValue.value.executeMonth,
        
      }
      console.log('MaintenanceFormData', data)
      setModalProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: recordValue.value.isNewRecord,
        tid: recordValue.value.tid,
      };
      console.log('params', params);
      // console.log('submit', params, data, record);
      const res = await inMaintenanceInfoUpdateUserCode(params, data);
      showMessage(res.message);
      setTimeout(closeModal);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

// 定义一个响应式变量来存储MaintenancerRecord
const recordValue = ref(props.MaintenancerRecord);
  // 监听props.MaintenancerRecord的变化
  watch(
    () => props.MaintenancerRecord,
    (newValue) => {
      recordValue.value = newValue;
      console.log('MaintenancerRecord变化了，新值为:', newValue);
    },
    { immediate: true }
  );
  onMounted(() => {
    console.log('组件挂载时MaintenancerRecord的值为:', recordValue.value);
    console.log('props的值为:', props.MaintenancerRecord);
  });
</script>
